﻿using PARK.Common.Core.Manager;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PARK.Accessctl.Interfaces.AccessCtl;
using PARK.Accessctl.Entitys;
using PARK.Accessctl.Entitys.Dto.AccessCtl;
using System.Data;
using PARK.Accessctl.Entitys.Dto.AccessDoor;
using PARK.Accessctl.Entitys.Dto.AccessCtlauth;

namespace PARK.Accessctl.AccessDoor
{
    /// <summary>
    /// 门禁设备服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Access", Name = "door", Order = 200)]
    [Route("api/access/[controller]")]
    public class AccessDoorService : IAccessDoorService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AccessDoorEntity> _accessDoorRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="AccessDoorService"/>类型的新实例
        /// </summary>
        public AccessDoorService(
            ISqlSugarRepository<AccessDoorEntity> accessDoorRepository,
            IUserManager userManager)
        {
            _accessDoorRepository = accessDoorRepository;
            _db = _accessDoorRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
		/// 获取门列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AccessDoorListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                StringBuilder dbsql = new StringBuilder("select a.doorId,a.ctlId,b.ctlSN,b.ctlName,b.doorAreaId,b.doorAreaName,b.ctlposition,a.doorNo,a.doorName,b.isOnline,b.lastOnLineTime from access_door a inner join access_ctl b on a.ctlId=b.ctlId ");
                dbsql.Append(" where b.IsDeleted=0 and b.EnabledMark=1");
                if (!string.IsNullOrEmpty(input.doorAreaId))
                {
                    dbsql.AppendFormat(" and b.doorAreaId='{0}'", input.doorAreaId);
                }
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    dbsql.AppendFormat(" AND (b.CtlName like '%{0}%' or b.CtlSn like '%{0}%' or b.IoTcardNo like '%{0}%' or a.doorName like '%{0}%')", input.keyword);
                }
                //公司权限
                dbsql.AppendFormat(" and a.CompanyId='{0}'", userInfo.companyId);
                dbsql.Append(" order by b.doorAreaName, b.ctlName, a.doorNo");
                var data = await _db.SqlQueryable<AccessDoorListOutput>(dbsql.ToString()).ToListAsync();
                return data;
            }
            else
            {
                return null;
            }               
        }
    }
}
